<template>
    <div>
        <!-- 网页头部 -->
        <el-card class="head-card">
            <i class="el-icon-s-fold"></i><span style="">大健康综合管理后台</span>
            <h2>商品管理</h2>

            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="全部" name="first">

                </el-tab-pane>
                <el-tab-pane label="已上架" name="second"> <el-empty description="暂无数据"></el-empty></el-tab-pane>
                <el-tab-pane label="审核未通过" name="third">
                    <el-empty description="暂无数据"></el-empty>
                </el-tab-pane>
            </el-tabs>

        </el-card>

        <!-- 网页中部 -->
        <el-card class="body-card">
            <h4 style="margin-top: 0">查询条件</h4>
            <el-form :inline="true" :model="condition" class="demo-form-inline">
                <el-form-item label="商品名称:">
                    <el-input v-model="condition.name" placeholder="请输入内容" clearable
                              style="margin-right: 50px"></el-input>
                </el-form-item>
                <el-form-item label="分类:">
                    <el-select v-model="condition.categoryName" clearable placeholder="请选择分类">
                        <el-option
                            v-for="item in categoryNameList"
                            :label=item
                            :value=item>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态:">
                    <el-select v-model="condition.status" placeholder="商品状态">
                        <el-option label="已上架" value="1"></el-option>
                        <el-option label="已下架" value="0"></el-option>
                        <el-option label="审核未通过" value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="queryCommodity">查询</el-button>
                    <el-button type="warning" @click="resetting">重置</el-button>
<!--                    <el-button type="primary" plain @click="search">高级查询</el-button>-->
                    <el-button type="success" @click="openDialog">高级筛选</el-button>
                </el-form-item>
            </el-form>

            <el-dialog
                    title="高级筛选"
                    :visible.sync="centerDialogVisible"
                    width="40%" center>
                <span>
                    <el-form :inline="true" :model="searchObj" class="demo-form-inline">
<!--                        <el-form-item label="商品分类">-->
<!--                            <el-select v-model="commodityQueryDto.categoryId" clearable placeholder="请选择">-->
<!--                            <el-option-->
<!--                                v-for="item in categoryNameList"-->
<!--                                :label=item-->
<!--                                :value=item>-->
<!--                            </el-option>-->
<!--                          </el-select>-->
<!--                        </el-form-item>-->
<!--                        <el-form-item label="状态">-->
<!--                            <el-select v-model="commodityQueryDto.status" placeholder="商品状态">-->
<!--                                <el-option label="已上架" value="1"></el-option>-->
<!--                                <el-option label="已下架" value="0"></el-option>-->
<!--                                <el-option label="审核未通过" value="2"></el-option>-->
<!--                            </el-select>-->
<!--                        </el-form-item>-->
<!--                        <el-form-item label="商品名称">-->
<!--                            <el-input v-model="commodityQueryDto.name" placeholder=""></el-input>-->
<!--                        </el-form-item>-->
                        <el-form-item label="商品编号" label-width="80px">
                            <el-input v-model="searchObj.code" placeholder=""></el-input>
                        </el-form-item><br/>
                        <span>
                             <el-form-item label="价格" label-width="80px">
                                <el-input-number v-model="searchObj.lowPrice" controls-position="right"
                                             @change="handleChange" :min="1" :max="100000">
                                </el-input-number>
                            </el-form-item>
                            <el-form-item label="至">
                            <el-input-number v-model="searchObj.highPrice" controls-position="right"
                                             @change="handleChange" :min="1" :max="100000"></el-input-number>
                            </el-form-item>
                        </span>

                    </el-form>
                </span>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="centerDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addSearch">确 定</el-button>
                </span>
            </el-dialog>
        </el-card>

        <!-- 网页底部 -->
        <el-card class="foot-card">
            <span>
                <el-button type="primary" icon="el-icon-plus"
                           style="padding-left: 30px; padding-right: 30px;  margin-right:30px "
                @click="addCommodity">新增</el-button>
                 <el-button type="primary" plain style="padding-left: 35px; padding-right: 35px;  margin-right:30px "
                            @click="listingCommodity">上架</el-button>
                <el-button type="warning" plain style="padding-left: 35px; padding-right: 35px;  margin-right:30px "
                @click="updateStatus">下架</el-button>
            </span>
            <el-table
                    ref="multipleTable"
                    :data="tableData"
                    tooltip-effect="dark"
                    style="width: 100%"
                    @selection-change="handleSelectionChange">
                <el-table-column
                        type="selection"
                        width="55">
                </el-table-column>
                <el-table-column prop="id" label="商品ID"></el-table-column>

                <el-table-column prop="name" label="商品名称"></el-table-column>

                <el-table-column prop="categoryName" label="商品分类"></el-table-column>

                <el-table-column prop="srcImg" label="商品图片">
                    <template slot-scope="scope">
                        <img :src="scope.row.srcImg" alt="商品图片" width="100" height="80">
                    </template>
                </el-table-column>

                <el-table-column prop="title" label="商品标题"></el-table-column>

                <el-table-column prop="code" label="商品编码"></el-table-column>

                <el-table-column prop="price" label="商品价格">
                    <template slot-scope="scope">
                        <span>{{ scope.row.price }}</span> ¥
                    </template>
                </el-table-column>

                <el-table-column prop="stock" label="商品库存">
<!--                    <template slot-scope="scope">-->
<!--                        <el-input v-model="scope.row.stock" placeholder="库存值" @change="handleStockChange(scope.row)"></el-input>-->
<!--                    </template>-->
                </el-table-column>

                <el-table-column prop="status" label="商品状态">
                    <template slot-scope="scope">
                        <el-tag plain
                                :type="scope.row.status === 1 ? 'success' : (scope.row.status === 0 ? 'info' : 'danger')">
                            {{ scope.row.status === 1 ? '已上架' : (scope.row.status === 0 ? '已下架' : '审核不通过') }}
                        </el-tag>
                    </template>
                </el-table-column>

                <el-table-column label="操作" width="280">

                    <template slot-scope="scope">

<!--                        <el-button @click="viewCommodity(scope.$index)" type="primary" size="small">查看</el-button>-->

                        <el-button @click="editCommodity(scope.$index)" type="warning" size="small">编辑</el-button>

                        <el-button type="danger" size="mini" @click="removeById(scope.index, scope.row)">删除</el-button>

                    </template>

                </el-table-column>

            </el-table>
            <!-- 分页 -->
            <el-pagination style="margin-top: 10px"
                           background
                           @size-change="handleSizeChange"
                           @current-change="handleCurrentChange"
                           :current-page="condition.pageNum"
                           :page-sizes="[5, 10, 15]"
                           :page-size="condition.pageSize"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="pageBean.total">
            </el-pagination>
        </el-card>
    </div>
</template>

<script>
export default {
    name: "Commodity",
    data() {
        return {
            // 搜索对象
            condition: {
                pageNum: 1,
                pageSize: 5,
                name: '',
                categoryId:'',
                code: "",
                status: null
            },
            //筛选条件
            searchObj:{
                pageNum: 1,
                pageSize: 5,
                code: '',
                lowPrice:1,
                highPrice:100,
            },
            commodityQueryDto: {
                categoryName: '',
                name:'',
                status: '',
                lowPrice:1,
                highPrice:10000,
                code: ''
            },
            categoryNameList: [],
            lowPrice: 1,
            highPrice: 1,

            activeName: 'first',
            pageBean: {},

            input: '',
            centerDialogVisible: false,

            pageNum: 1,
            pageSize: 5,
            name: '',
            total: 0,
            //图片地址
            srcImg: '',
            //表格数据
            tableData: [],
            //复选框
            multipleSelection: [],
            commodities: [] // 用于存储查询结果
        }

    },
    methods: {
        //打开对话框
        openDialog(){
            this.centerDialogVisible = true;
        },
        addSearch(){
            this.$axios.post('/commodity/addSearch', this.searchObj).then(resp => {
                console.log('resp', resp)
                this.pageBean = resp.data.data;
                this.tableData = resp.data.data.list;
                this.total = resp.data.data.total;
                console.log("弹窗数据", this.tableData);
                this.centerDialogVisible = false;
            });
        },
        //高级筛选
        advancedQuery(){
            let advanceQuery = this.commodityQueryDto
            this.$axios.post('/commodity/findByCondition', {
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                name: advanceQuery.name,
                categoryId: advanceQuery.categoryId,
                status: advanceQuery.status,
                code: advanceQuery.code,
                lowPrice: advanceQuery.lowPrice,
                highPrice: advanceQuery.highPrice,
            }).then(response => {
                this.commodities = response.data.data.records;
                //this.total = response.total;
                this.tableData = response.data.data.records;
                console.log("高级查询数据：",this.commodities);
                console.log("高级查询tableData：",this.tableData);
                this.centerDialogVisible = false;
                }).catch(error => {
                    console.error('查询商品时出现错误', error);
                });
        },
        //条件查询加载
        reloadData() {
            this.$axios.post('/commodity/findAllCommodities', this.condition).then(resp => {
                console.log('resp', resp)
                this.pageBean = resp.data.data;
                this.tableData = resp.data.data.list;
                this.total = resp.data.data.total;
                console.log("tableData表格数据", this.tableData)
            });
        },
        //加载所有一级品类
        findAllCategoryName() {
            this.$axios.get('/category/findAllCategoryName').then(resp => {
                // 将服务器返回的数据解析并赋值给 options 数组
                this.categoryNameList = resp.data.data;
                console.log("一级品类名",this.categoryNameList)
            }).catch(error => {
                console.error(error);
            });
        },

        //通过es完成索引库的搜索
        queryCommodityByKeyword() {
            // 异步请求后台，通过es完成索引库搜索
            this.$axios.get('/commodity/search', {
                params: {
                    keyword: this.condition.keyword,
                    pageNum: this.pageNum,
                    pageSize: this.pageSize
                }
            }).then(resp => {
                this.tableData = resp.data.data.list;
                this.total = resp.data.data.total;

            })
        },

        queryCommodity() {
            // 跳转道搜索页面 search.html
            // location.href = '/commodity/toSearch?keyword=' + this.condition.keyword;
            this.reloadData();
        },
        //上架
        listingCommodity(){
            //判断是否选中
            if (this.multipleSelection.length == 0) {
                this.$message.warning("请先选中要上架的商品");
                return;
            }
            //确认
            this.$confirm(`此操作将上架${this.multipleSelection.length}个商品,是否继续?`, '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                //1.把对象数组转成id的数组 (row表示数组中每个元素)
                let ids = this.multipleSelection.map(row => row.id);
                console.log("ids"+ids);
                //2.发送操作给服务器端
                this.$axios.post("/commodity/listingCommodity", ids).then(resp => {
                   console.log("商品状态",resp)
                    if (resp.data.data==21007){
                        this.$message.error("商品已上架请勿重复上架！")
                    }
                    this.$message.success(`成功上架`);
                    //重新加载表格数据
                    this.reloadData();
                });
            }).catch(() => {
                //不做什么
            });
        },
        //下架
        updateStatus() {
            //判断是否选中
            if (this.multipleSelection.length == 0) {
                this.$message.warning("请先选中要下架的商品");
                return;
            }
            //确认
            this.$confirm(`此操作将下架${this.multipleSelection.length}个商品,是否继续?`, '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                //1.把对象数组转成id的数组 (row表示数组中每个元素)
                let ids = this.multipleSelection.map(row => row.id);
                console.log("ids"+ids);
                //2.发送操作给服务器端
                this.$axios.post("/commodity/offShelf", ids).then(resp => {
                    this.$message.success(`成功下架`);
                    //重新加载表格数据
                    this.reloadData();
                });
            }).catch(() => {
                //不做什么
            });
        },
        //删除
        removeById(index,row){
            console.log("row",row)
            this.$confirm(`此操作将永久删除：${row.name}, 是否继续?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //调用服务器端来删除
                this.$axios.get(`/commodity/deleteById?id=${row.id}`).then(resp => {
                    if (resp.data.code) {
                        this.$message.success(resp.data.message);
                    } else {
                        this.$message.error("删除失败");
                    }
                    //重新加载
                    this.reloadData();
                });
            }).catch(() => {
                //什么也不写
            });
        },
        viewCommodity(index) {
            // 处理查看按钮点击事件，可以根据索引获取对应商品的信息并进行展示
            console.log('查看', this.tableData[index]);
        },
        editCommodity(index) {
            // 处理编辑按钮点击事件，可以根据索引获取对应商品的信息并进行编辑操作
            console.log('编辑', this.tableData[index]);
        },
        deleteCommodity(index) {
            // 处理删除按钮点击事件，可以删除对应商品的信息
            console.log('删除', this.tableData[index]);
        },
        //
        search() {
        },
        //添加
        addCommodity(){
            this.$router.push({
                path: `/addCommodity`
            });
        },
        //重置
        resetting() {
            this.condition = {
                name: "",
                pageNum: 1,
                pageSize: 5
            };
            this.reloadData()
        },

        handleChange(value) {
            console.log(value);
        },
        onSubmit() {
            console.log('submit!');
        },

        handleClick(tab, event) {
            console.log(tab, event);
        },

        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.condition.pageSize = val;
            this.reloadData();
        },
        handleCurrentChange(val) {
            this.condition.pageNum = val;
            this.reloadData();
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
            console.log("选中数据",this.multipleSelection)
        },
    },
    created() {
        this.reloadData();
        this.findAllCategoryName()
    }
}
</script>

<style scoped>
.head-card {
    text-align: left;
    height: 200px;

}

.el-icon-s-fold {
    font-size: 23px;
    margin-right: 10px;
    margin-bottom: 40px;
}

.body-card {
    text-align: left;
    padding-left: 18px;
    width: 100%;
    display: block;
    margin: 30px auto;
    height: 130px;
    padding-bottom: 20px;
}

.foot-card {
    text-align: left;
    padding-left: 18px;
    width: 100%;
    display: block;
    margin: 0 auto;
}

.el-button {

}
</style>